package org.example.tinyurl.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.example.util.ContextHolderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

/**
 * @author: zk
 * @date: 2023/6/21 19:11
 * 自己定制insert时按照什么算法去分发到不同表中
 */
public class MyTablePreciseAlgorithm implements PreciseShardingAlgorithm<Long> {

    private static final Logger logger = LoggerFactory.getLogger(MyTablePreciseAlgorithm.class);

    @Override
    public String doSharding(Collection<String> tables, PreciseShardingValue<Long> shardingValue) {
        Long id = ContextHolderUtil.idHolder.get();
        ContextHolderUtil.idHolder.remove();
        // todo 4 改为动态
        Long suffix = id % 4 + 1;

        String table = shardingValue.getLogicTableName() + "_" + suffix;
        if (logger.isDebugEnabled()) {
            logger.debug("suffix: {}, table: {}", suffix, table);
        }
        if (tables.contains(table)) {
            return table;
        }
        throw new UnsupportedOperationException("找不到表名");
    }
}
